package com.example.mys_app;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    MediaPlayer player;
    int[] music={
            R.raw.serven,
            R.raw.tian,
            R.raw.lan,
            R.raw.hj,
            R.raw.music
    };
    public MyService() {

    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("sh","MyService:onCreate...");
        player=MediaPlayer.create(this,music[0]);  //设置默认播放的歌曲
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("sh","MyService:onStart...");
        //获取歌曲索引，默认是0
        int songIndex=intent.getIntExtra("songIndex",0);
        //设置要播放的歌曲索引
        setSong(songIndex);

        player.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        player.stop();
        player.release();
        super.onDestroy();
        Log.d("sh","MyService:onDestroy...");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.

        throw new UnsupportedOperationException("Not yet implemented");
    }

    public void setSong(int songIndex){
        //该方法用来实现点击歌曲播放相应歌曲
        if(songIndex>=0&&songIndex<= music.length){
            player.stop();
            player.release();
            player=MediaPlayer.create(this,music[songIndex]);
        }

    }
}